<?php

/**
 * 文档系统 - 控制器类
 * 
 * @package    01CMS
 * @subpackage admin
 * @author     rolong at vip.qq.com
 * @version    1.0.0
 * @link       http://www.01cms.com
 */

class ArchiveController extends Controller
{
    public $title = '文档系统';
    public $Db;

    function __construct ()
    {
        parent::__construct();
        
        if (! model('User')->isLogined())
        {
            redirect('admin/login?url=' . getCurUrl());
        }
        
        if (! model('User')->checkAuth())
        {
            exit('您的权限不足');
        }
        
        $this->Db = model('Db');
    }

    function channel ($action = 0, $id = '', $table = '', $select = 0)
    {
        $this->title = $this->title . ' => 模型管理';
        
        if ($action == 'insert' || $action == 'update')
        {
            $this->data = $this->Load->post('name|模型名称不能空,tableId|表后缀不能为空');
            
            if ($error = $this->Load->getError())
            {
                response($error);
            }
            
            if ($action == 'insert')
            {
                $this->Db->query("CREATE TABLE `@@__archive_channel_{$this->data['tableId']}` 
                    (`id` int(11) NOT NULL AUTO_INCREMENT,`archiveId` int(11) NOT NULL,`categoryId` int(11) NOT NULL,
                    PRIMARY KEY (`id`))ENGINE=MyISAM;");
            
            }
            else if ($action == 'update')
            {
                $table = $this->Load->post('tableId,oldTableId');
                
                if ($table['tableId'] != $table['oldTableId'])
                {
                    $this->Db->query("RENAME TABLE `@@__archive_channel_{$table['oldTableId']}` 
                     TO `@@__archive_channel_{$table['tableId']}` ;");
                }
            }
        }
        else if ($action == 'del')
        {
            model('Channel', $id)->delete();
        }
        else if ($action == 'lists' && $select == '1')
        {
            $this->templateSuffix = 'select';
        }
        else if ($action == 'lists' && $id == - 1)
        {
            model('Channel', $id)->writeChannel();
        }
        
        $this->id = $id;
        $this->action($action);
    }

    function field ($action = 0, $id = '', $channelId = '', $field = '')
    {
        $Channel = model('Channel', $channelId);
        
        $this->title = $this->title . ' => 模型管理 => ' . $Channel->name . ' => 字段管理';
        
        $this->where = 'channelId=' . $channelId;
        
        if ($action == 'insert' || $action == 'update')
        {
            $this->data = $this->Load->post('ordering,name,field|字段名不能为空,type|类型不能为空,code,emptyTip');
            
            if ($error = $this->Load->getError())
            {
                response($error);
            }
            
            $this->data['channelId'] = $channelId;
            
            if ($action == 'insert')
            {
                $this->Db->query("ALTER TABLE `@@__archive_channel_{$Channel->tableId}` ADD `{$this->data['field']}` {$this->data['type']}");
            }
            else if ($action == 'update')
            {
                $oldField = $this->Load->post('oldField', 'one');
                
                if ($oldField != $this->data['field'])
                {
                    $this->Db->query("ALTER TABLE `@@__archive_channel_{$Channel->tableId}` CHANGE `{$oldField}` `{$this->data['field']}` {$this->data['type']}");
                }
            }
        }
        else if ($action == 'del')
        {
            $this->Db->query("ALTER TABLE `@@__archive_channel_{$Channel->tableId}` DROP `{$field}`");
        }
        else if ($action == 'lists')
        {
            if ($id == - 1)
            {
                $Channel->updateFiledList();
            }
            
            $this->order = 'channelId asc, ordering asc';
        }
        
        $this->id = $id;
        $this->action($action);
    }

    function category ($action = 0, $id = '')
    {
        $this->title = $this->title . ' => 栏目管理';
        
        if ($action != 'ordering')
        {
            $Cagetory = model('Category', $id);
        }
        
        if ($action == 'lists')
        {
            $this->lists = $Cagetory->getChildren(0, 1);
            
            $channels = model('Channel')->getData();
            
            $count = count($this->lists);
            
            for ($i = 0; $i < $count; $i ++)
            {
                if ($this->lists[$i]->type == 1)
                {
                    $this->lists[$i]->channelName = $channels["{$this->lists[$i]->channelId}"]['name'];
                }
            }
            
            if ($id == - 1)
            {
                $Cagetory->writeCategory();
            }
        }
        else if ($action == 'add' || $action == 'mod')
        {
            $this->categories = $Cagetory->getChildren(0, 1);
            
            $this->channels = model('Channel')->getData();
        }
        else if ($action == 'insert' || $action == 'update')
        {
            $type = $this->Load->post('type', 'one');
            
            if ($type == 1)
            {
                $this->data = $this->Load->post('parentId,name|栏目名称不能为空,alias,channelId|您还没有选择模型,isHidden,desc,keywords,type,categoryTemplateName|栏目模板不能为空,archiveTemplateName|文档模板不能为空,pageSize|列表大小不能为空,archiveUrl|文档URL不能为空,link,visit');
            }
            else if ($type == 2)
            {
                $this->data = $this->Load->post('parentId,name|栏目名称不能为空,alias,isHidden,desc,keywords,type,categoryTemplateName|栏目模板不能为空,pageSize,visit');
            }
            else
            {
                $this->data = $this->Load->post('parentId,name|栏目名称不能为空,isHidden,desc,keywords,type,link|链接地址不能为空');
            }
            
            if ($error = $this->Load->getError())
            {
                response($error);
            }
            
            //处理别名
            if ($type != 0)
            {
                $pinyin = $this->Load->post('pinyin', 'one');
                switch ($pinyin)
                {
                    case 1:
                    {
                        $this->data['alias'] = String::pinyin($this->data['name'], 0);
                        break;
                    }
                    case 2:
                    {
                        $this->data['alias'] = String::pinyin($this->data['name'], 1);
                        break;
                    }
                    default:
                    {
                        $this->data['alias'] = empty($this->data['alias']) ? String::pinyin($this->data['name']) : $this->data['alias'];
                    }
                
                }
            }
        }
        else if ($action == 'del')
        {
            $Cagetory->delete();
        }
        
        $this->id = $id;
        
        $this->action($action);
    }

    function archive ($action = 0, $id = 0, $categoryId = 0, $channelId = 0, $templateSuffix = '')
    {
        $this->uploadSetting = data('uploadSetting');
        $this->curUrl = getCurUrl();
        
        if ($action == 'insert' || $action == 'update')
        {
            $data = $this->Load->post('title|标题不能为空,ordering,flag,viceTitle,color,redirectUrl,categoryId|您还没有选择栏目,source,author,pass,keywords,desc,thumb,listed,visit,pubTime,fileName,templateName');
            
            if ($error = $this->Load->getError())
            {
                responseToParent($error);
            }
            
            $data['flag'] = empty($data['flag']) ? '' : implode(',', $_POST['flag']);
            $data['addTime'] = TIME;
            $data['pass'] = ($action == 'insert') ? $this->Load->var['pass'] : $data['pass'];
            $data['pubTime'] = strtotime($data['pubTime']);
            $data['ordering'] = $data['pubTime'] + $data['ordering'] * 86400;
            
            $Category = model('Category', $data['categoryId']);
            $Channel = model('Channel', $Category->channelId);
            
            $addData = $this->Load->post($Channel->fieldList);
            
            if ($error = $this->Load->getError())
            {
                responseToParent($error);
            }
            
            if (isset($addData['content']) && empty($data['desc']))
            {
                $data['desc'] = cnSubstr(strip_tags($addData['content']), 0, 100);
            }
        }
        
        switch ($action)
        {
            case 'lists':
            {
                $where = '1';
                
                $queryVars = $this->Load->query('id,title,pass');
                
                if ($queryVars)
                {
                    $this->keyWord = slashQuotes($queryVars, 'strip');
                    
                    $where = empty($queryVars['id']) ? $where : $where . " AND id='{$queryVars['id']}'";
                    $where = empty($queryVars['title']) ? $where : $where . " AND title like '%{$queryVars['title']}%'";
                    $where = (isset($queryVars['pass']) && $queryVars['pass'] != '') ? $where . " AND pass='{$queryVars['pass']}'" : $where;
                }
                
                if ($categoryId > 0)
                {
                    $Category = model('Category', $categoryId);
                    $Channel = model('Channel', $Category->channelId);
                    
                    $sonId = model('Category', $categoryId)->allSonIds;
                    
                    if (empty($sonId))
                    {
                        $where .= " AND categoryId = {$categoryId}";
                    }
                    else
                    {
                        $where .= " AND categoryId in ({$categoryId},{$sonId})";
                    }
                }
                else if ($channelId > 0)
                {
                    $Channel = model('Channel', $channelId);
                    
                    $where .= " AND categoryId in ({$Channel->categoryIds})";
                }
                
                $this->where = $where;
                
                $this->categoryId = $categoryId;
                $this->channelId = $channelId;
                
                $this->order = 'ordering desc';
                
                $this->Db->pageParam = 5;
                
                $lists = $this->Db->lists();
                
                $count = count($lists);
                
                for ($i = 0; $i < $count; $i ++)
                {
                    $lists[$i]->title = htmlspecialchars($lists[$i]->title);
                    $flag = explode(',', $lists[$i]->flag);
                    
                    if (in_array('p', $flag))
                    {
                        $lists[$i]->title .= '[图]';
                    }
                    $lists[$i]->categoryName = model('Category', $lists[$i]->categoryId)->name;
                    $weight = in_array('b', $flag) ? 'font-weight:bold;' : '';
                    $color = empty($lists[$i]->color) ? '' : "color:{$lists[$i]->color};";
                    $style = $color . $weight;
                    if (! empty($style))
                    {
                        $lists[$i]->title = '<span style="' . $style . '">' . $lists[$i]->title . '</span>';
                    }
                    
                    $lists[$i]->link = in_array('j', $flag) ? $lists[$i]->redirectUrl : BOOT_URL . '/' . $lists[$i]->fileName;
                }
                
                $this->lists = $lists;
                
                $templateSuffix = empty($templateSuffix) ? '' : $templateSuffix;
                
                $this->Load->view('smarty', $templateSuffix);
                
                break;
            }
            case 'add':
            {
                if (empty($channelId) && empty($categoryId))
                {
                    redirect('archive/channel/lists/0/0/1');
                }
                else
                {
                    if ($categoryId > 0)
                    {
                        $Category = model('Category', $categoryId);
                        $channelId = $Category->channelId;
                        
                        //如果是栏目封面，转向频道选择页面
                        if (empty($channelId))
                        {
                            redirect('archive/channel/lists/0/0/1');
                        }
                    }
                    
                    $Channel = model('Channel', $channelId);
                    
                    $this->addFields = $Channel->getAddFields($channelId);
                    $this->category = model('Category', $categoryId)->getChildren(0, 1, 1);
                    $this->categoryId = $categoryId;
                    $this->channelId = $channelId;
                    $tableId = ucfirst($Channel->tableId);
                    
                    if (file_exists(APP_PATH . '/view/' . $this->c . '/' . $this->m . 'Add' . $tableId . '.tpl'))
                    {
                        $this->Load->view('smarty', 'add' . $tableId);
                    }
                    else
                    {
                        $this->Load->view('smarty', 'add');
                    }
                }
                break;
            }
            case 'insert':
            {
                model('Archive')->insertArchive($data, $addData, $Channel->tableId);
                
                responseToParent('添加成功', BOOT_URL . '/archive/archive/lists/0/' . $data['categoryId'], 1);
                
                break;
            }
            case 'mod':
            {
                $Archive = model('Archive', $id);
                $Category = model('Category', $Archive->categoryId);
                $Channel = model('Channel', $Category->channelId);
                $this->data = $Archive->data;
                $this->addData = $Channel->getAddData($id, - 1);
                $this->addFields = $Channel->getAddFields();
                $this->category = $Category->getChildren(0, 1, 1);
                $this->categoryId = $this->data->categoryId;
                $this->channelId = $Channel->id;
                
                $tableId = ucfirst($Channel->tableId);
                
                if (file_exists(APP_PATH . '/view/' . $this->c . '/' . $this->m . 'Mod' . $tableId . '.tpl'))
                {
                    $this->Load->view('smarty', 'mod' . $tableId);
                }
                else
                {
                    $this->Load->view('smarty', 'mod');
                }
                
                break;
            }
            case 'update':
            {
                model('Archive')->updateArchive($data, $addData, $Channel->tableId, $id);
                
                responseToParent('修改成功', BOOT_URL . '/archive/archive/lists/0/' . $data['categoryId'] . '/' . $channelId);
                
                break;
            }
            case 'del':
            {
                model('Archive')->delArchive($id);
                
                $this->curUrl = getCurUrl();
                
                response('删除成功', TRUE);
                
                break;
            }
        }
    }

    function setPass ($id, $status)
    {
        $sta = model('Db')->update(array('pass'=>$status), "id in ({$id})", '@@__archive_archive');
        response('设置成功', $sta, "setPass({$id},{$status});");
    }

    function single ($action = '', $id = 0)
    {
        if ($action == 'update' || $action == 'insert')
        {
            $this->data = $this->Load->post('title|标题不能为空, fileName|文件名不能为空, keywords, template|模板名不能为空, description, content|内容不能为空');
            if ($error = $this->Load->getError())
            {
                response($error);
            }
            $this->data['updateTime'] = TIME;
        }
        else if($action == 'lists')
        {
            $where = '1';
            $queryVars = $this->Load->query('id,title');
            if ($queryVars)
            {
                $this->keyWord = slashQuotes($queryVars, 'strip');
                $where = empty($queryVars['id']) ? $where : $where . " AND id='{$queryVars['id']}'";
                $where = empty($queryVars['title']) ? $where : $where . " AND title like '%{$queryVars['title']}%'";
            }
            $this->where = $where;
        }
        else if($action == 'updateHtml')
        {
            if($id == 0)
            {
                model('Html')->writeAllSingleHtml();
            }
            else
            {
                model('Html')->writeSingleHtml($id);
            }
            response('更新成功');
            exit();
        }
        $this->title = $this->title . ' => 单页文档';
        $this->id = $id;
        $this->order = 'id desc';
        $this->action($action);
    }
}
